//
//  LSSettingViewController.m
//  LibraryStorm
//
//  Created by Anh Nguyen on 4/15/14.
//  Copyright (c) 2014 3ATeam. All rights reserved.
//

#import "LSSettingViewController.h"
#import "LSSettingHeaderView.h"
#import "LSOptionViewController.h"
#import "UIColor+HexString.h"
#import "Constants.h"

#import "BookIAPHelper.h"
#import <StoreKit/StoreKit.h>

#define kSliderHeight			7.0
#define kViewTag				1		// for tagging our embedded controls for removal at cell recycle time
#define kWhiteButtonTag         10
#define kSepiaButtonTag         11
#define kBlackButtonTag         12

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kLabelKey = @"labelKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

// tableView cell id constants
static NSString *settingCellID = @"SettingCellID";
static NSString *seetingHeaderViewID = @"seetingHeaderViewID";

@interface LSSettingViewController () <LSOptionViewControllerDelegate>

@property (nonatomic, strong) UISwitch *switchControl;
@property (nonatomic, strong) UISlider *sliderControl;
@property (nonatomic, strong) UIStepper *stepper;
@property (nonatomic, strong) UIControl *themeControl;
@property (nonatomic, strong) UIButton *restoreButton;
@property (nonatomic, strong) NSArray *dataSourceArray;
@property (nonatomic, strong) NSArray *fontTypes;
@property (nonatomic, strong) NSArray *animateTypes;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableDictionary *generalSettingDict;
@property (nonatomic, assign) int fontSize;
@property (nonatomic, copy) NSString *fontName;

@property (nonatomic, strong) SKProduct *product;
@end

@implementation LSSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:GeneralSetting] isKindOfClass:[NSDictionary class]]) {
        self.generalSettingDict = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:GeneralSetting]];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IS_DEVICE_IPAD) {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:Color_Orange_View];
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    // Do any additional setup after loading the view.
    [self setListBarItem:@[@(BarItemButton_Cancel),@(BarItemButton_Save)]];
    [self setTitle:NSLocalizedString(@"Setting", nil)];

    self.dataSourceArray = @[
                               /*@[
                                   @{  kSectionTitleKey:@"Remove Advertise",
                                       kLabelKey:@"Remove Advertise",
                                       kSourceKey:@"LSSettingViewController.m:\r-(UIButton *)restoreButton",
                                       kViewKey:self.restoreButton },
                                   
                                   @{  kSectionTitleKey:@"Auto post on facebook",
                                       kLabelKey:@"Auto post on facebook",
                                       kSourceKey:@"LSSettingViewController.m:\r-(UISwitch *)switchControl",
                                       kViewKey:self.switchControl },
                                ],*/
                               @[
                                   @{  kSectionTitleKey:@"Font Face",
                                       kLabelKey:@"Font Face",
                                       kSourceKey:@"",
                                       kViewKey:@"" },
                                 
                                   @{  kSectionTitleKey:@"UIStepper",
                                       kLabelKey:@"Text Size",
                                       kSourceKey:@"LSSettingViewController.m:\r-(UIStepper *)stepper",
                                       kViewKey:self.stepper },
                                 
                                   @{  kSectionTitleKey:@"Page Turn",
                                       kLabelKey:@"Page Turn",
                                       kSourceKey:@"",
                                       kViewKey:@"" },
                                     
                                   @{  kSectionTitleKey:@"Brightness",
          
                                       kLabelKey:@"Brightness",
                                       kSourceKey:@"LSSettingViewController.m:\r-(UISlider *)sliderControl",
                                       kViewKey:self.sliderControl },
                                   @{  kSectionTitleKey:@"Theme",
                                       kLabelKey:@"Theme",
                                       kSourceKey:@"LSSettingViewController.m:\r-(UIControl *)themeControl",
                                       kViewKey:self.themeControl },
                                   ]
                             ];
    
    [self setTintColor];
    [self.tableView registerNib:[LSSettingHeaderView nib] forHeaderFooterViewReuseIdentifier:seetingHeaderViewID];
    self.fontTypes = @[@"Arial", @"Futura", @"Georgia", @"Helvetica Neue", @"Palatino", @"Verdana", @"Times New Roman", @"Roboto"];
    self.animateTypes = @[@"Slide", @"Curl", @"Fade", @"Cut"];
    
//    [[BookIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *products) {
//        if (success) {
//            if (products.count > 0) {
//                _product = products[0];
//                [self.tableView reloadData];
//            }
//        }
//    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productPurchased:) name:IAPHelperProductPurchasedNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)productPurchased:(NSNotification *)notification
{
//    NSString * productIdentifier = notification.object;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([[segue identifier] isEqualToString:@"showOptionViewId"]) {
        LSOptionViewController *optionViewController = [segue destinationViewController];
        if ([sender isKindOfClass:[NSIndexPath class]]) {
            NSInteger rowIndex = [(NSIndexPath *)sender row];
            if (rowIndex == 0) {
                optionViewController.items = self.fontTypes;
                optionViewController.titleName = @"Font Face";
                optionViewController.optionType = OptionType_FontFace;
                optionViewController.defaultSeletedObject = [self.generalSettingDict objectForKey:FontFace];
            }else if (rowIndex == 2) {
                optionViewController.items = self.animateTypes;
                optionViewController.titleName = @"Page Turn";
                optionViewController.optionType = OptionType_PageTurn;
                optionViewController.defaultSeletedObject = [self.generalSettingDict objectForKey:PageTurn];
            }
        }
        optionViewController.delegate = self;
    }
}

#pragma mark - Table view datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSourceArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [(NSArray *)self.dataSourceArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:settingCellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:settingCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = Roboto_Regular(15);
    }
    
    UIView *viewToRemove = nil;
    viewToRemove = [cell.contentView viewWithTag:kViewTag];
    if (viewToRemove)
        [viewToRemove removeFromSuperview];
    
    cell.textLabel.text = [[[self.dataSourceArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] valueForKey:kLabelKey];
    
    UIControl *control = [[[self.dataSourceArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] valueForKey:kViewKey];
    if (control && [control isKindOfClass:[UIControl class]]) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        // make sure this control is right-justified to the right side of the cell
        CGRect newFrame = control.frame;
        newFrame.origin.x = CGRectGetWidth(cell.contentView.frame) - CGRectGetWidth(newFrame) - 10.0;
        control.frame = newFrame;
        
        // if the cell is ever resized, keep the control over to the right
        control.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        
        [cell.contentView addSubview:control];
    }else {
        NSString *detailName = nil;
        if ([cell.textLabel.text isEqualToString:@"Font Face"]) {
            if ([[self.generalSettingDict objectForKey:FontFace] intValue] <= self.fontTypes.count) {
                detailName = [self.fontTypes objectAtIndex:[[self.generalSettingDict objectForKey:FontFace] intValue]];
            }
        }else if ([cell.textLabel.text isEqualToString:@"Page Turn"]) {
            if ([[self.generalSettingDict objectForKey:PageTurn] intValue] <= self.animateTypes.count) {
                detailName = [self.animateTypes objectAtIndex:[[self.generalSettingDict objectForKey:PageTurn] intValue]];
            }
        }
        
        cell.detailTextLabel.text = detailName;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSString *title = [[[self.dataSourceArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] valueForKey:kLabelKey];
        if ([title isEqualToString:@"Font Face"] || [title isEqualToString:@"Page Turn"]) {
            [self performSegueWithIdentifier:@"showOptionViewId" sender:indexPath];
        }
    }
    /*else if (indexPath.section == 0 && indexPath.row == 0) {
        if (self.product) {
            // In app purchase
            [[BookIAPHelper sharedInstance] buyProduct:self.product];
        }
    }*/
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 150;
    }
    
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        LSSettingHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:seetingHeaderViewID];
        self.fontName = [kAppDelegate fontFamilyNameWithType:[[self.generalSettingDict objectForKey:FontFace] intValue]];
        self.fontSize = [[self.generalSettingDict objectForKey:TextSize] intValue];
        headerView.textView.font = [UIFont fontWithName:self.fontName size:self.fontSize];
        ThemeStyle style = [[self.generalSettingDict objectForKey:Theme] intValue];
        UIColor *backgroundColor = nil;
        UIColor *textColor = nil;
        switch (style) {
            case ThemeStyle_White:
                backgroundColor = [UIColor whiteColor];
                textColor = [UIColor blackColor];
                break;
            case ThemeStyle_Sepia:
                backgroundColor = [UIColor colorWithHexString:Color_Sepia_View];
                textColor = [UIColor blackColor];
                break;
            case ThemeStyle_Black:
                backgroundColor = [UIColor blackColor];
                textColor = [UIColor whiteColor];
                break;
            default:
                break;
        }
        headerView.textView.backgroundColor = backgroundColor;
        headerView.textView.textColor = textColor;
        
        return headerView;
    }
    
    return nil;
}

#pragma mark - Target Action
- (void)clickCancelButton:(id)sender
{
    if (IS_DEVICE_IPAD && self.popOverController) {
        [self.popOverController dismissPopoverAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (void)clickSaveButton:(id)sender
{
    [kAppDelegate setGeneralSettingForEpub:self.generalSettingDict];

    if (IS_DEVICE_IPAD && self.popOverController) {
        [self.popOverController dismissPopoverAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (void)switchAction:(id)sender
{
	// NSLog(@"switchAction: value = %d", [sender isOn]);
}

- (void)sliderAction:(id)sender
{
    // UISlider *slider = (UISlider *)sender;
    // NSLog(@"sliderAction: value = %f", [slider value]);
}

- (void)stepperAction:(id)sender
{
    UIStepper *actualStepper = (UIStepper *)sender;
    NSLog(@"stepperAction: value = %f", [actualStepper value]);
    [self.generalSettingDict setObject:@((int)[actualStepper value]) forKey:TextSize];
    self.fontSize = (int)[actualStepper value];
    [self previewTextViewWithFontName:self.fontName fontSize:self.fontSize];
}

- (void)selectThemeAction:(UIButton *)sender
{
    ThemeStyle style = ThemeStyle_White;
    UIColor *backgroundColor = nil;
    UIColor *textColor = nil;
    /*Reset button selected after*/
    for (UIView *view in self.themeControl.subviews) {
        if ([view isKindOfClass:[UIButton class]] && view.tag >= 10) {
            UIButton *button = (UIButton *)view;
            button.layer.borderColor = [UIColor whiteColor].CGColor;
            button.layer.borderWidth = 0.0;
            if (button.tag == kWhiteButtonTag) {
                button.layer.borderColor = [UIColor lightGrayColor].CGColor;
                button.layer.borderWidth = 0.5;
            }
        }
    }
    
    switch (sender.tag) {
        case kWhiteButtonTag:
            sender.layer.borderColor = [UIColor blueColor].CGColor;
            sender.layer.borderWidth = 1.0;
            backgroundColor = [UIColor whiteColor];
            textColor = [UIColor blackColor];
            style = ThemeStyle_White;
            break;
            
        case kSepiaButtonTag:
            sender.layer.borderColor = [UIColor brownColor].CGColor;
            sender.layer.borderWidth = 1.0;
            backgroundColor = [UIColor colorWithHexString:Color_Sepia_View];
            textColor = [UIColor blackColor];
            style = ThemeStyle_Sepia;
            break;
            
        case kBlackButtonTag:
            sender.layer.borderColor = [UIColor orangeColor].CGColor;
            sender.layer.borderWidth = 1.0;
            backgroundColor = [UIColor blackColor];
            textColor = [UIColor whiteColor];
            style = ThemeStyle_Black;
            break;
        default:
            break;
    }
    [self.generalSettingDict setObject:@(style) forKey:Theme];
    [self previewTextViewWithBackground:backgroundColor textColor:textColor];
}

- (void)restoreAction:(id)sender
{
    [[BookIAPHelper sharedInstance] restoreCompletedTransactions];
}

#pragma mark - Lazy creation of controls

- (UISwitch *)switchControl
{
    if (_switchControl == nil)
    {
        CGRect frame = CGRectMake(0.0, 12.0, 94.0, 27.0);
        _switchControl = [[UISwitch alloc] initWithFrame:frame];
        [_switchControl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        
        // in case the parent view draws with a custom color or gradient, use a transparent color
        _switchControl.backgroundColor = [UIColor clearColor];
		
		[_switchControl setAccessibilityLabel:NSLocalizedString(@"StandardSwitch", @"")];
		
		_switchControl.tag = kViewTag;	// tag this view for later so we can remove it from recycled table cells
    }
    return _switchControl;
}

- (UISlider *)sliderControl
{
    if (_sliderControl == nil)
    {
        CGRect frame = CGRectMake(0.0, 12.0, 120.0, kSliderHeight);
        _sliderControl = [[UISlider alloc] initWithFrame:frame];
        [_sliderControl addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
        
        // in case the parent view draws with a custom color or gradient, use a transparent color
        _sliderControl.backgroundColor = [UIColor clearColor];
        
        _sliderControl.minimumValue = 0.0;
        _sliderControl.maximumValue = 100.0;
        _sliderControl.continuous = YES;
        _sliderControl.value = 50.0;
        
		// Add an accessibility label that describes the slider.
		[_sliderControl setAccessibilityLabel:NSLocalizedString(@"StandardSlider", @"")];
		
		_sliderControl.tag = kViewTag;	// tag this view for later so we can remove it from recycled table cells
    }
    return _sliderControl;
}

- (UIStepper *)stepper
{
    if (_stepper == nil && [UIStepper class])
    {
        CGRect frame = CGRectMake(0.0, 10.0, 0.0, 0.0);
        _stepper = [[UIStepper alloc] initWithFrame:frame];
		[_stepper sizeToFit];        // size the control to it's normal size
        
		_stepper.tag = kViewTag;     // tag this view for later so we can remove it from recycled table cells
        _stepper.value = [[self.generalSettingDict objectForKey:TextSize] doubleValue];
        _stepper.minimumValue = 12;
        _stepper.maximumValue = 22;
        _stepper.stepValue = 2;
        
        [_stepper addTarget:self action:@selector(stepperAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _stepper;
}

- (UIControl *)themeControl
{
    if (_themeControl == nil && [UIControl class]) {
        CGRect frame = CGRectMake(0.0, 0.0, 136.0, 44);
        _themeControl = [[UIControl alloc] initWithFrame:frame];
        _themeControl.tag = kViewTag;     // tag this view for later so we can remove it from recycled table cells
        ThemeStyle style = [[self.generalSettingDict objectForKey:Theme] intValue];
        UIButton *whiteTheme = [UIButton buttonWithType:UIButtonTypeCustom];
        whiteTheme.frame = CGRectMake(0, 6, 32, 32);
        whiteTheme.backgroundColor = [UIColor whiteColor];
        whiteTheme.layer.cornerRadius = 16.0f;
        whiteTheme.layer.borderColor = [UIColor lightGrayColor].CGColor;
        whiteTheme.layer.borderWidth = 0.5;
        if (style == ThemeStyle_White) {
            whiteTheme.layer.borderColor = [UIColor blueColor].CGColor;
            whiteTheme.layer.borderWidth = 1.0;
        }
        
        whiteTheme.tag = kWhiteButtonTag;
        [whiteTheme addTarget:self action:@selector(selectThemeAction:) forControlEvents:UIControlEventTouchUpInside];
        UIButton *sepiaTheme = [UIButton buttonWithType:UIButtonTypeCustom];
        sepiaTheme.frame = CGRectMake(whiteTheme.frame.origin.x+whiteTheme.frame.size.width + 20, 6, 32, 32);
        sepiaTheme.backgroundColor = [UIColor colorWithHexString:Color_Sepia_View];
        sepiaTheme.layer.cornerRadius = 16.0f;
        if (style == ThemeStyle_Sepia) {
            sepiaTheme.layer.borderColor = [UIColor brownColor].CGColor;
            sepiaTheme.layer.borderWidth = 1.0;
        }
        
        sepiaTheme.tag = kSepiaButtonTag;
        [sepiaTheme addTarget:self action:@selector(selectThemeAction:) forControlEvents:UIControlEventTouchUpInside];
        UIButton *blackTheme = [UIButton buttonWithType:UIButtonTypeCustom];
        blackTheme.frame = CGRectMake(sepiaTheme.frame.origin.x+sepiaTheme.frame.size.width + 20, 6, 32, 32);
        blackTheme.backgroundColor = [UIColor blackColor];
        blackTheme.layer.cornerRadius = 16.0f;
        
        if (style == ThemeStyle_Black) {
            blackTheme.layer.borderColor = [UIColor orangeColor].CGColor;
            blackTheme.layer.borderWidth = 1.0;
        }
        
        blackTheme.tag = kBlackButtonTag;
        [blackTheme addTarget:self action:@selector(selectThemeAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [_themeControl addSubview:whiteTheme];
        [_themeControl addSubview:sepiaTheme];
        [_themeControl addSubview:blackTheme];
    }
    
    return _themeControl;
}

- (UIButton *)restoreButton
{
    if (_restoreButton == nil && [UIButton class])
    {
        _restoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _restoreButton.frame = CGRectMake(0.0, 5.0, 70.0, 34.0);
		_restoreButton.tag = kViewTag;     // tag this view for later so we can remove it from recycled table cells
        [_restoreButton setTitle:@"Restore" forState:UIControlStateNormal];
        _restoreButton.titleLabel.font = Roboto_Bold(15);
        [_restoreButton setBackgroundColor:[UIColor colorWithHexString:Color_Orange_View]];
        [_restoreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_restoreButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [_restoreButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
        [_restoreButton addTarget:self action:@selector(restoreAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _restoreButton;
}

- (void)setTintColor
{
    UIColor *tintColor = [UIColor colorWithHexString:Color_Orange_View];
    
    self.sliderControl.minimumTrackTintColor = tintColor;
    self.sliderControl.thumbTintColor = tintColor;
    self.switchControl.onTintColor = tintColor;
    self.stepper.tintColor = tintColor;
    
    UIColor *thumbTintColor = (self.switchControl.thumbTintColor != nil) ? nil : [UIColor lightGrayColor];
    self.switchControl.onTintColor = tintColor;
    self.switchControl.thumbTintColor = thumbTintColor;
}

#pragma mark - LSOptionViewControllerDelegate
- (void)didSelectOption:(OptionType)optionType andStyle:(NSInteger)style {
    switch (optionType) {
        case OptionType_FontFace:
        {
            [self.generalSettingDict setObject:@(style) forKey:FontFace];
            self.fontName = [kAppDelegate fontFamilyNameWithType:(int)style];
            
            [self previewTextViewWithFontName:self.fontName fontSize:self.fontSize];
        }
            break;
        case OptionType_PageTurn:
        {
            [self.generalSettingDict setObject:@(style) forKey:PageTurn];
        }
            break;

        default:
            break;
    }
    
    [self.tableView reloadData];
}

#pragma mark - Header View
- (LSSettingHeaderView *)headerTableView
{
    LSSettingHeaderView *headerView = nil;
    if ([[self.tableView headerViewForSection:0] isKindOfClass:[LSSettingHeaderView class]]) {
        headerView = (LSSettingHeaderView *)[self.tableView headerViewForSection:0];
    }
    
    return headerView;
}

- (void)previewTextViewWithFontName:(NSString *)fontName fontSize:(int)fontSize
{
    [self headerTableView].textView.font = [UIFont fontWithName:fontName size:fontSize];
}

- (void)previewTextViewWithBackground:(UIColor *)backgroundColor textColor:(UIColor *)textColor
{
    [[self headerTableView].textView setBackgroundColor:backgroundColor];
    [[self headerTableView].textView setTextColor:textColor];
}
@end
